package com.example.ss_shiro.realm;

import com.example.ss_shiro.entity.Account;
import com.example.ss_shiro.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

//继承AuthorizingRealm
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    private AccountService accountService;

    /**
     * 授权
     * 对应用户的权限信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前的登录的用户信息
        Subject subject= SecurityUtils.getSubject();
        Account account =(Account) subject.getPrincipal();
        //设置角色
        Set<String> roles=new HashSet<>();
        roles.add(account.getRole());
        //将查询出来的权限信息交给shiro
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        //设置权限
        info.addStringPermission(account.getPerms());
        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    //对应用户的角色信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //创建一个UsernamePasswordToken对象,shiro 用来封装用户登录信息，使用用户的登录信息来创建token;
        //向下转型 父类转子类
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        Account account = accountService.findByUsername(token.getUsername());
        if(account!=null){
            //密码对比 与token 里面的密码对比
            return  new SimpleAuthenticationInfo(account,account.getPassword(),getName());
        }
        return null;
    }
}
